package com.xht.handler.security;

import com.alibaba.fastjson.JSON;
import com.xht.domain.ResponseResult;
import com.xht.enums.AppHttpCodeEnum;
import com.xht.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 响应失败 返回给 前端的 信息,封装成ResponseResult
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

//        InsufficientAuthenticationException 需要登录后才能访问,即使无访问权限
//        BadCredentialsException 账号密码错误异常
        ResponseResult result = null;
        if (e instanceof BadCredentialsException) {
            result =
                    ResponseResult
                            .errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        } else if (e instanceof InsufficientAuthenticationException) {
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else {
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), "认证或授权出现失败");
        }

        //响应给前端
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));


    }
}
